<?php

namespace app\api\controller;

use addons\epay\library\Service;
use addons\qrcode\Qrcode;
use app\admin\model\jeek\Attestation;
use app\common\controller\Api;
use app\common\model\Article;
use app\common\model\Banner;
use app\common\model\Category;
use app\common\model\CopartnerCate;
use app\common\model\CopartnerMoneyLog;
use app\common\model\CopartnerPaylog;
use app\common\model\Order;
use app\common\model\Problem;
use app\common\model\Withdraw;
use think\Db;


/**
 * 合伙人
 */
class Copartner extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * Account:合伙人等级
     * User: Ixiangang
     * Date: 2025/3/29
     * Time: 16:30
     */
    public function copartner_cate()
    {
        $list = CopartnerCate::where(['status' => 'normal'])->order('weigh desc')->field("id as copartner_cate_id,name")->select();
        $this->success("成功", $list);
    }

    /**
     * Account:合伙人入驻
     * User: Ixiangang
     * Date: 2025/2/17
     * Time: 10:06
     */
    public function add()
    {
        $user_id = $this->auth->id;
        $copartner_cate_id = $this->request->post('copartner_cate_id');
        if (!$copartner_cate_id){
            $this->error("合伙人等级错误");
        }
        $name = $this->request->post('name');
        $age = $this->request->post('age');
        $address = $this->request->post('address');
        $mobile = $this->request->post('mobile');
        $identity_sn = $this->request->post('identity_sn');
        $identity_front = $this->request->post('identity_front');
        $identity_back = $this->request->post('identity_back');
        if (empty($name)) $this->error("填写姓名");
        if (empty($age)) $this->error("填写年龄");
        if (empty($address)) $this->error("填写地址");
        if (empty($mobile)) $this->error("填写电话");
        $copartner = \app\common\model\Copartner::where('user_id', $user_id)->find();
        if (!empty($copartner)) {
            $this->error("你已入住合伙人");
        }
        $data = [
            'user_id' => $user_id,
            'copartner_cate_id' => $copartner_cate_id,
            'name' => $name,
            'age' => $age,
            'address' => $address,
            'mobile' => $mobile,
            'identity_sn' => $identity_sn,
            'identity_front' => $identity_front,
            'identity_back' => $identity_back,
            'createtime' => time(),
        ];
        $rs = \app\common\model\Copartner::insertGetId($data);
        if ($rs) $this->success("OK", ["copartner_id" => $rs]);
        $this->error("入住失败");
    }


    /**
     * Account:合伙人信息
     * User: Ixiangang
     * Date: 2025/2/19
     * Time: 10:54
     */
    public function info()
    {
        $user_id = $this->auth->id;
        $info = \app\common\model\Copartner::where('user_id', $user_id)->find();
        if (empty($info)) {
            $this->error("合伙人信息不存在");
        }
        $this->success("OK", $info);
    }


    /**
     * Account:合伙人支付金额
     * User: Ixiangang
     * Date: 2025/2/17
     * Time: 10:33
     */
    public function pay_copartner()
    {
        $user_id = $this->auth->id;
        $copartner_id = $this->request->post('copartner_id');
        $pay_type = $this->request->post('pay_type'); //支付类型:wechat=微信,alipay=支付宝
        if (!in_array($pay_type, ['wechat', 'alipay'])) $this->error("支付类型错误");
        if ($pay_type == "wechat") {
            if (!$this->auth->app_openid) $this->error('请先绑定微信');
        }
        $info = \app\common\model\Copartner::where('id', $copartner_id)->find();
        # 查询需要认证费
        $certified_price = Db::name('copartner_cate')->where(['id' => $info->copartner_cate_id])->value('certified_price');
        if (empty($info) || !$certified_price) $this->error("合伙人信息不存在");
        $data = [
            'order_sn' => 'H_' . date('YmdHis') . rand(1111, 9999),
            'user_id' => $user_id,
            'copartner_id' => $info->id,
            'pay_price' => $certified_price,
            'pay_type' => $pay_type,
        ];
        $row = CopartnerPaylog::create($data);
        if ($row) {
            $params = [
                'amount' => $data['pay_price'],
                'orderid' => $data['order_sn'],
                'type' => $pay_type,
                'title' => "合伙人缴纳认证费",
                'notifyurl' => $this->request->root(true) . '/api/pay/notify/paytype/' . $pay_type,
                'method' => 'app',
                'openid' => $this->auth->app_openid,
            ];
            $pay = Service::submitOrder($params);
            $this->success('支付成功', compact('pay', 'pay_type'));
        }
        $this->error("支付错误");
    }


    /**
     * Account:生成二维码
     * User: Ixiangang
     * Date: 2025/2/17
     * Time: 13:52
     */
    public function qrcode()
    {
        $update = $this->request->get('update', 0);  //1=更新二维码
        $user_id = $this->auth->id;
        $info = \app\common\model\Copartner::where('user_id', $user_id)->find();
        if (empty($info)) $this->error("合伙人不存在");
        if ($info->ispay != '1') $this->error("合伙人未缴纳金额");
        if (!$info->qrcode || $update == 1) {
            $url = \request()->domain() . "/index/invite/invite?init_code=" . $user_id;
            $qrcode = generateQrcode($url);
            if (!$qrcode) $this->error("生成二维码失败");
            $info->qrcode = $qrcode;
            $info->save();
        } else {
            $qrcode = $info->qrcode;
        }
        $this->success("OK", ['qrcode' => \request()->domain() . $qrcode]);
    }


    /**
     * Account:邀请记录下级用户
     * User: Ixiangang
     * Date: 2025/2/17
     * Time: 15:03
     */
    public function list()
    {
        $user_id = $this->auth->id;
        $count = \app\common\model\User::where('pid', $user_id)->count();
        $list = \app\common\model\User::where('pid', $user_id)->field('id,avatar,nickname,createtime')->select();
        array_map(function ($item) {
            # 计算累计收入金额
            $item->money = CopartnerMoneyLog::where(['junior_user_id' => $item->id, 'withdraw_id' => 0])->sum('money');
        }, $list);
        $this->success("OK", ['count' => $count, 'list' => $list]);
    }

    /**
     * Account:详情
     * User: Ixiangang
     * Date: 2025/2/17
     * Time: 19:02
     */
    public function details()
    {
        $id = $this->request->get('id'); // 下级用户ID
        # 查询记录
        $list = CopartnerMoneyLog::where(['junior_user_id' => $id, 'withdraw_id' => 0])->field('id,order_amount,money,createtime')->select();
        $this->success("OK", ['list' => $list]);
    }


    /**
     * Account:合伙人佣金明细
     * User: Ixiangang
     * Date: 2025/2/17
     * Time: 19:09
     */
    public function commission()
    {
        $user_id = $this->auth->id;
        # 查询合伙人
        $copartner = \app\common\model\Copartner::where('user_id', $user_id)->find();
        if (empty($copartner)) {
            $this->error("合伙人信息不存在");
        }
        $type = $this->request->get('type'); //1=返佣明细,-1=提现明细
        if (!in_array($type, [1, -1])) $this->error("参数错误");
        $where['copartner_id'] = $copartner->id;
        if ($type == 1) {
            $where['withdraw_id'] = 0;
        }
        if ($type == -1) {
            $where['withdraw_id'] = ['neq', 0];
        }
        $list = CopartnerMoneyLog::where($where)->field('id,order_amount,junior_user_id,money,memo,createtime')->order('id desc')->select();
        if (!empty($list) && $type == 1) {
            foreach ($list as $k => $v) {
                # 查询合伙人佣金明细
                $v->user = \app\common\model\User::where('id', $v['junior_user_id'])->field('nickname,avatar')->find();
            }
        }
        $this->success("OK", ['list' => $list, 'money' => $copartner->money]);
    }


    /**
     * Account:合伙人提现
     * User: Ixiangang
     * Date: 2025/2/17
     * Time: 19:23
     */
    public function copartnerWithdraw()
    {
        $user = $this->auth->getUser();
        if (!$user->wechat_account || !$user->wechat_name) {
            $this->error("请先绑定微信账号");
        }
        # 查询合伙人
        $copartner = \app\common\model\Copartner::where('user_id', $user->id)->find();
        if (empty($copartner)) $this->error("合伙人不存在");
        $price = $this->request->post('price'); //提现金额
        if (!is_numeric($price)) {
            $this->error("请输入数字");
        }
        if ($price <= 0) {
            $this->error("提现金额必须大于0");
        }
        if ($price > $copartner->money) {
            $this->error('可提现资金不足！');
        }
        $info = Withdraw::where(['copartner_id' => $copartner->id, 'status' => '1', 'position' => '3'])->find();
        if (!empty($info)) {
            $this->error(__('你有一笔提现订单再审核，请勿重复提交'));
        }
        $data = [
            'copartner_id' => $copartner->id,
            'price' => $price,
            'position' => 3, //咨询师
            'type' => 1, //微信
            'status' => 1, //待审核
            'wechat_account' => $user->wechat_account,
            'wechat_name' => $user->wechat_name,
            'reason_rejection' => '',
            'createtime' => time(),
        ];
        $rs = Withdraw::insertGetId($data);
        if ($rs) {
            $memo = "提现";
            \app\common\model\Copartner::money(-$price, $copartner->user_id, 0, $memo, $rs);
            $this->success("申请提现成功");
        }
        $this->error("参数错误");

    }


}